import Vue from 'vue'
import Vuex from 'vuex'
import plugins from './plugins/storage'
import Navigate from '../router'
import {
  goodsState,
  newsState
} from '@/enum/index.js'
import $http from '../api'
import io from '@hyoga/uni-socket.io';
import eventBus from '@/eventbus/index.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    user: {},
    goodsState: {
      [goodsState.pending]: '待审核',
      [goodsState.published]: '发布中',
      [goodsState.unsanctioned]: '未通过',
      [goodsState.overdue]: '已过期',
      [goodsState.suspensive]: '已下架',
      ...goodsState
    },
    newsState: {
      [newsState.pending]: '审核中',
      [newsState.noPass]: '未通过',
      [newsState.pass]: '已通过',
      ...newsState
    },
    socket: null,
    offlineMsgList: [],
    onlineMsg: {},
    // 消息列表,本地持久化保存，不然刷新状态就没了
    msgList: [],
    downloadProgressData: {
      progress: 0,
      totalBytesWritten: 0,
      totalBytesExpectedToWrite: 0
    },
    updateData: {
      update: false,
      note: '',
      wgtUrl: '',
      apkUrl: ''
    }
  },
  plugins: [plugins],
  modules: {
    
  },
  mutations: {
    setUpdateData(state, data) {
      state.updateData = data
    },
    setProgress(state, data) {
      state.downloadProgressData = data
    },
    login(state, data) {
      console.log('mutations', data)
      state.user = data
      this.commit('connectSocket')
    },
    logout(state) {
      state.user = {}
      state.msgList = []
      this.commit('setSocket', null)
      Navigate.reLaunch('/pages/login/login')
    },
    setSocket(state, socket) {
      state.socket = socket
    },
    setOfflineMsg(state, list) {
      console.log('setOfflineMsg', list)
      list.forEach(item => {
        this.commit('setOnlineMsg', item)
      })
    },
    setOnlineMsg(state, data) {
      state.onlineMsg = data
      console.log('新消息', state.onlineMsg)
      this.commit('editNewMsg', data)
      uni.showTabBarRedDot({
        index: 2
      })
    },
    setMsgList(state, list) {
      state.msgList = list
    },
    // 收到新消息设置对应消息的角标数量
    editNewMsg(state, newMsg) {
      console.log('editNewMsg', newMsg)
      let newMsgUserId
      if (newMsg.fromUser._id) {
        newMsgUserId = newMsg.fromUser._id
      } else {
        newMsgUserId = newMsg.fromUser
      }
        // 处理已经在消息列表的用户消息逻辑
      if (state.msgList.some(item => item.friend._id === newMsgUserId)) {
        // 新消息插入最前面
        const index = state.msgList.findIndex((item) => item.friend._id === newMsgUserId)
        // copy
        const current = {
          ...state.msgList[index]
        }
        // 删除
        state.msgList.splice(index, 1)
        // 再插入copy的消息在最前面
        state.msgList.unshift({
          ...current,
          content: newMsg.content,
          // 判断收到的新消息是否是已读状态，比如是正在对方的聊天窗口页面，则收到就是已读消息
          unreadMsgNum: newMsg.isRead ? current.unreadMsgNum : current.unreadMsgNum + 1
        })
      } else {
        // 处理还没有聊过天的用户逻辑
        state.msgList.unshift({
          ...newMsg,
          friend: newMsg.fromUser,
          unreadMsgNum: 1
        })
      }
    },
    // 新增好友，把好友加入列表
    addNewFriend(state, data) {
      if(!state.msgList.some(item => item.friend._id === data.friend._id)) {
        state.msgList.unshift(data)
      }
    },
    // 发送消息成功，把自己发送的消息添加到消息列表最新消息
    sendMsgSuccess(state, data) {
      state.msgList = state.msgList.map(item => {
        if(item.friend._id === data.toUser._id) {
          return {
            ...item,
            content: data.content,
            createTime: data.createTime
          }
        }
        return item
      })
    },
    // 查看消息后，清空未读消息数unreadMsgNum
    resetUnreadMsg(state, userId) {
      // 客户端数据处理
      state.msgList.some((item, i) => {
        if(userId === item.friend._id) {
          state.msgList[i].unreadMsgNum = 0
        }
        return userId === item.friend._id
      })
      // 后台数据处理,把当前用户的消息全部标记为已读状态
      $http.put('/chat', {
        fromUser: userId
      }).then(() => {
        console.log('消息已标记为已读')
      })
    },
    connectSocket(state, socket) {
      console.log('state.user._id', state.user._id)
      console.log('state.user._id', state.socket)
      // 没有登录和已经连接不执行
      if(!state.user._id) return
      if(!state.socket) {
        state.socket = io('wss://mini-cloud.top:3001', {
          auth: {
            token: state.user.token
          },
          // autoConnect: true,
          transports: ['websocket'],
          // timeout: 1000,
        })
        state.socket.on('connect', () => {
          console.log('app的ws 已连接', state.socket.id);
          
          // 根据id监听我的消息
          state.socket.on(state.user._id, (data) => {
            console.log('app收到消息：', data);
            this.commit('setOnlineMsg', data)
          });
        
          // 监听离线消息
          state.socket.on('offlineMsg', (list) => {
            // 收到服务器推送的消息，可以跟进自身业务进行操作
            console.log('离线消息消息：', list);
            this.commit('setOfflineMsg', list)
          });
          
          // 连接断开
          state.socket.on("disconnect", () => {
            console.log('连接断开了', state.socket.id)
            // 连接断开自动重连一次
            state.socket.connect();
            this.commit('setSocket', null)
          });
        });
        
        state.socket.on('error', (msg) => {
          console.log('ws error', msg);
        });
      } else {
        // id为undefined是断开了链接
        if(!state.socket.id) {
          uni.showToast({
            title: '重连'
          })
          // 连接断开重连
          state.socket.connect();
        }
      }
    },
    setMsgRedDot(state) {
      console.log('msgList', state.msgList)
      if(!state.msgList.length) return
      state.msgList.some(item => {
        if (item.unreadMsgNum > 0) {
          uni.showTabBarRedDot({
            index: 2
          })
        } else {
          uni.hideTabBarRedDot({
            index: 2
          })
        }
        return item.unreadMsgNum > 0
      })
    },
  },
  actions: {
    login({
      commit
    }, data) {
      console.log('actions', data)
      commit('login', data)
    },
    getMsgList({
      state, commit
    }, data={refresh: false}) {
      return new Promise((resolve, reject) => {
        if(!state.user.token) {
          return reject()
        } 
        // 没有数据或刷新数据
        if (!state.msgList.length || data.refresh) {
          // 没有数据执行
          const res = $http.get('/friend').then(res => {
            console.log('getMsgList--------------------------------------')
            commit('setMsgList', res.data)
            resolve()
          }).catch((err) => {
            reject()
          })
        } else {
          resolve()
        }
      })
    }
  }
})

export default store;
